import {LoadingController, AlertController, ToastController, Events} from "ionic-angular";
import { Injectable } from "@angular/core";
import 'rxjs/add/operator/toPromise';
import {HttpClient,HttpParams,HttpHeaders} from "@angular/common/http";
import { ToastrService } from 'ngx-toastr';
import {Storage} from "@ionic/storage";
import {PageParam} from "../models/page-param-model";
import {FormGroup} from "@angular/forms";
import {ResDataModel} from "../models/res-data-model";
import {HTTP} from "@ionic-native/http";

@Injectable()
export class AppGlobal {
  //缓存key的配置
  static cache:any = {
    slides:"_dress_slides",
    categories:"_dress_categories",
    products:"_dress_products"
  }
  //token
  static token = "";
  //功能列表
  static menus = [];
  //经纬度
  static longitude:number = 0;
  static latitude:number = 0;

  static platform: string; //平台
  static savePath: string; //存储路径
  static cachePath: string; //缓存路径

  static packageName: string;  //包名
  static appVersion: string = '0.0.0';  //版本号

  static jPushInited:boolean = false; //极光推送初始化状态
  static pushEnable:boolean = true; //是否启用推送提醒，默认开启

  static myProfilePicName:string = "MyProfilePic.jpg";//头像默认名称
  //static myProfilePicUri:string //头像文件URI

  static seconds:number = 60;//全局计时器计数
}

@Injectable()
export class AppService {

  domain:string;

  constructor(public http: HttpClient,
              public events: Events,
              private loadingCtrl: LoadingController,
              private alertCtrl: AlertController,
              private toastCtrl: ToastController,
              private toastr: ToastrService,
              private storage:Storage,
              private nativeHttp:HTTP
              ) {

  }

  //对参数进行编码
  encode(params) {
    var str = '';
    if(params) {
      for(var key in params) {
        if(params.hasOwnProperty(key)){
          var value = params[key];
          str += encodeURIComponent(key) + '=' +encodeURIComponent(value) + '&';
        }
      }
      str = '?' + str.substring(0,str.length - 1);
    }
    return str;
  }

  //Get请求
  httpGet(url, params, callback, loader:boolean = false) {
    let loading = this.loadingCtrl.create({});
    if(loader) {
      loading.present();//显示加载层
    }
    this.http.get('/temp/ajax.sword' + url + this.encode(params))
      .toPromise()
      .then(res => {
        var d = res;
        if(loader){
          loading.dismiss();//移除加载层
        }
        callback(d == null ? "[]" : d);
      })
      .catch(error => {
        if(loader) {
          loading.dismiss();
        }
        this.handleError(error);
      })
  }

  //Post请求
  httpPost(ctrl:string, postData:any, pageData:PageParam, callback, loader:boolean = false){
    //加载层
    let loading = this.loadingCtrl.create();
    if (loader) {
      loading.present();
    }
    let token = AppGlobal.token;
    postData.ctrl = ctrl;
    //声明参数与头部信息
    let headers,params;
    //判断平台
    if(AppGlobal.platform == "WEB"){
      //设置http头
      headers = new HttpHeaders()
        .set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      //设置请求参数
      params = new HttpParams()
        .set('postData', JSON.stringify(postData))
        .set('pageAndSort',pageData?pageData.toPageParamString():null)
        .set('token',token)
        .set('clientType','app');

      this.http.post(this.domain, params,{headers:headers})
        .subscribe(res => {
          this.handleRes(res,callback);
          if (loader) {
            loading.dismiss();
          }
        },error =>{
          if (loader) {
            loading.dismiss();
          }
          this.handleError(error);
        });
    }else{
      headers = {
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"
      }
      params = {
        postData:JSON.stringify(postData),
        pageAndSort:pageData?pageData.toPageParamString():null,
        token:token,
        clientType:'app'
      }
      //alert("postData2:"+JSON.stringify(params));
      this.nativeHttp.post(this.domain,params,headers)
        .then((res)=>{
          //alert("res:"+JSON.stringify(res));
          this.handleRes(JSON.parse(res['data']),callback);
          if (loader) {
            loading.dismiss();
          }
        }).catch(err=>{
        alert(JSON.stringify(err));
      })
    }
  }

  /**
   * 处理返回报文
   * @param res
   * @param callback
   */
  private handleRes(res:any,callback){
    switch(res['code']) {
      case "2000": {//成功
        //res['data'] == null ? [] : res['data']
        let datas = res['data'] == null ? [] : res['data'];
        let resDatas = new ResDataModel(datas);
        callback(resDatas);
        break;
      }
      case "4402": {//功能不存在
        console.log(res);
        this.toast('该功能不存在');
        break;
      }
      case "4408": {//token无效或过期
        //提示token过期并重新登录
        this.alert('Token已过期，请重新登录',() => {
          //清楚过期的token
          AppGlobal.token = '';
          this.storage.remove('token');
          //发布跳转登录页的事件
          this.events.publish('toLogin');
        })
        break;
      }
      case "5000": {//业务类报错
        this.toast(res['msg']);
        break;
      }
      default: {
        console.log(res);
        this.toast('服务异常');
      }
    }
  }
  //Http传输请求异常处理
  private handleError(error: Response | any) {
    let msg = '';
    if (error.status == 400) {
      msg = '请求无效(code：400)';
      console.log('请检查参数类型是否匹配');
    }
    if (error.status == 404) {
      msg = '请求资源不存在(code：404)';
      console.error(msg + '，请检查路径是否正确');
    }
    if (error.status == 500) {
      msg = '服务器发生错误(code：500)';
      console.error(msg + '，请检查路径是否正确');
    }
    console.log(error);
    if (msg != '') {
      this.toast(msg);
    }
  }

  //封装alert提示框
  alert(message, callback?) {
    if (callback) {//有回调方法
      let alert = this.alertCtrl.create({
        title: '提示',
        message: message,
        buttons: [{
          text: "确定",
          handler: data => {
            callback();
          }
        }]
      });
      alert.present();
    } else {//没有回调
      let alert = this.alertCtrl.create({
        title: '提示',
        message: message,
        buttons: ["确定"]
      });
      alert.present();
    }
  }

  //封装confirm Alert
  confirm(message, callback_agree?, callback_disagree?){
    let alert = this.alertCtrl.create({
      title: '提示',
      message: message,
      buttons: [
        {
          text: "确定",
          handler: data => {
            if(callback_agree){
              callback_agree();
            }
          }
        },
        {
          text: "取消",
          handler: data => {
            if(callback_disagree){
              callback_disagree();
            }
          }
        }]
    });
    alert.present();
  }

  //封装toast提示框
  toast(message, callback?) {
    let toast = this.toastCtrl.create({
      message: message,
      duration: 2000,
      dismissOnPageChange: true,
    });
    toast.present();
    if (callback) {
      callback();
    }
  }

  //封装toast提示框
  smallToast(message,type?) {
/*    if(type){
      type = "info";
    }*/

    let config = {
      timeOut:1500,
      positionClass: 'toast-bottom-center',
      disableTimeOut:false
    }

    switch (type){
      case "success":{
        this.toastr.success(message,'',config);
        break;
      }
      case "info":{
        this.toastr.info(message,'',config);
        break;
      }
      case "warning":{
        this.toastr.warning(message,'',config);
        break;
      }
      case "error":{
        this.toastr.error(message,'',config);
        break;
      }
      default:{
        this.toastr.info(message,'',config);
      }
    }
  }


  //表单校验，校验不通过则弹出提示
  validate(formGroup: FormGroup,validate_msg:any):Boolean {
    debugger;
    for(var key in formGroup.controls){
      if(formGroup.controls[key].invalid){//若有验证不通过的
        if(validate_msg[key]){
          this.smallToast(validate_msg[key],"warning");
        }else{
          this.smallToast("表单校验不通过","warning");
        }
        return false;
      }
    }
    return true;
  }
}
